/*********************************************************************************
 *      Copyright:  (C) 2025 LingYun<iot25@lingyun>
 *                  All rights reserved.
 *
 *       Filename:  select.c
 *    Description:  This file 
 *                 
 *        Version:  1.0.0(23/03/25)
 *         Author:  LingYun <iot25@lingyun>
 *      ChangeLog:  1, Release initial version on "23/03/25 19:47:18"
 *                 
 ********************************************************************************/
#include<stdio.h>
#include<string.h>
#include<errno.h>
#include<unistd.h>
#include<ctype.h>
#include<time.h>
#include<getopt.h>
#include<pthread.h>
#include<libgen.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<arpa/inet.h>
#include<netinet/in.h>
#include<stdlib.h>

#define ARRAY_SIZE(x)      (sizeof(x)/sizeof(x[0]))
int socket_server_init(char *listen_ip, int listen_port);
static inline void msleep( unsigned long ms);
static inline void print_usage( char *progname);
int main(int argc , char  *argv[])
{
	int							listenfd ,connfd;//监听和连接套接字
	int							serv_port = 0;//服务器端口
	int 						daemon_run = 0;//是否后台运行（守护进程）
	char						*progname = NULL;//程序名
	int							rv;// 返回值检查
	char						buf[1024];//缓冲区
	fd_set						rdset;//select（） 读文件描述符
	int							found;//标志位
	int 						maxfd = 0;//select（） 最大文件描述符
	int 						i,j;//循环计数器
	int							fds_array[1024];//客户端套接字数组
	int 						opt;//命令行参数解析
	
	
	struct option				long_options[]=
	{
		{ "daemon", no_argument,NULL, 'b'},
		{ "port", required_argument,NULL, 'p'},
		{ "help", no_argument,NULL, 'h'},
		{ NULL, 0 , NULL , 0}
	};//命令行参数定义

	progname=basename(argv[0]);//获取程序名称

	while( ( opt = getopt_long(argc , argv, "bp:h", long_options, NULL)) != -1)
	{
		switch(opt)
		{
			case 'b':
				daemon_run=1;
				break;

			case 'p':
				serv_port = atoi(optarg);
				break;

			case 'h':
				print_usage(progname);
				return EXIT_SUCCESS;

			default:
				break;
		}
	}

	if( !serv_port )//检查端口是否有效
	{
		print_usage(progname);
		return -1;
	}

	if( ( listenfd=socket_server_init(NULL , serv_port) )<0 )//初始化套接字
	{
		printf("ERROR: %s server listen on port %d failure\n", argv[0] , serv_port);
		return -2;
	}
	printf(" %s server start to listen on port %d\n",argv[0] , serv_port);

	if( daemon_run )//进入后台模式
	{
		daemon(0 , 0);//参数： nochdir， noclose
	}

	for(i=0; i<ARRAY_SIZE(fds_array); i++)//初始化客户端套接字数组（全部设置位-1）
	{
		fds_array[i] = -1;
	}
	fds_array[0] = listenfd;//数组第一个元素是监听套接字

	for( ;  ; )//主事件循环
	{
		FD_ZERO(&rdset);//清空文件描述符集合
		for(i=0; i<ARRAY_SIZE(fds_array) ; i++)//将有效套接字加入select监听集合
		{
			if(fds_array[i]<0 )
				continue;
			maxfd = fds_array[i]>maxfd ? fds_array[i] : maxfd;//更新最大fd
			FD_SET(fds_array[i], &rdset);
		}
		
		rv = select(maxfd+1, &rdset , NULL , NULL, NULL);//阻塞等待事件发生（无限等待）
		if( rv<0 )
		{
			printf("select failure: %s\n", strerror(errno));
			continue;
		}
		if( rv==0 )
		{
			printf("select get timeout\n");
			continue;
		}

		if( FD_ISSET(listenfd, &rdset))//处理监听套接字事件（新连接）
		{
			if(( connfd=accept( listenfd,(struct sockaddr *)NULL , NULL ) )<0)
			{
				printf(" accept new client failure: %s\n", strerror(errno));
				continue;
			}
			
			//寻找空位储存新连接
			found = 0;
			for(i=0; i<ARRAY_SIZE(fds_array); i++)
			{
				if( fds_array[i]<0 )
				{
					printf("accept new client %d and add int array\n", connfd);
					fds_array[i] = connfd;
					found = 1;
					break;
				}

			}

			if( !found )//如果数组已经满了，则拒绝连接
			{
				printf("accept new client[%d] but full , so refuse it\n", connfd);
				close(connfd);
			}		
		}

		else//处理已经连接客户端数据
		{

			for( i=0 ; i<ARRAY_SIZE(fds_array) ; i++)
			{
				if(fds_array[i]<0 || !FD_ISSET(fds_array[i], &rdset) )
					continue;
				//读取客户端数据
				if( ( rv=read(fds_array[i], buf , sizeof(buf) )) <= 0 )
				{
					printf(" socket[%d] read failure or get disconnect.\n",fds_array[i]);
					close(fds_array[i]);
					fds_array[i] = -1;
				}
				else
				{
					printf(" scoket[%d] read get %d bytes data\n", fds_array[i], rv);
                      
					//小写转大写
					for( j=0 ; j<rv ; j++ )
						buf[j]= toupper(buf[j]);
					
					//回传数据
					if( write(fds_array[i] , buf , rv) < 0 )
					{
						printf("socket[%d] write failure: %s\n", fds_array[i] , strerror(errno) );
						close(fds_array[i] );
						fds_array[i] = -1;
					}
					
				}
				
			}
		}
	}
Cleanup:
	close(listenfd);
	return 0;

}
static inline void msleep( unsigned long ms)
{
	struct timeval      tv;

	tv.tv_sec = ms/1000;//设置秒数
	tv.tv_usec = (ms%1000)*1000;//设置微秒数
	select( 0 , NULL , NULL , NULL , &tv); //利用select实现精准休眠
}

//打印帮助信息
static inline void print_usage( char *progname)
{
	printf("Usage: %s [OPTION]...\n", progname);

	printf(" %s is a socket server program , which used to verify client and echo back string from it\n", progname);
	printf(" \n Mandatory arguments to long options are mandatory for short options too :\n");

	printf(" -b[daemon ] set program running on background\n");
	printf(" -p[port ] Socket server port address\n");
	printf(" -h[help ] Display this help information\n");

	printf(" \nExample: %s -b -p 8900\n", progname);
	return;
}


//初始化tcp服务器套接字
int socket_server_init(char *listen_ip,int listen_port)
{
	struct sockaddr_in			servaddr; //IPV4结构
	int 						rv = 0;
	int							on = 1;//套接字选项开关
	int							listenfd;//监听套接字描述符

	if( (listenfd = socket(AF_INET, SOCK_STREAM , 0 )) < 0 )//创建套接字
	{
		printf(" use socket() to create a TCP socket failure: %s\n", strerror(errno));
		return -1;
	}

	setsockopt( listenfd, SOL_SOCKET, SO_REUSEADDR, &on , sizeof(on));//设置端口复用（防止TIME_WAIT状态导致连接失败）

	memset(&servaddr, 0 , sizeof(servaddr) );
	servaddr.sin_family = AF_INET;// IP v4协议
	servaddr.sin_port = htons(listen_port);//设置端口（主机字节序转成网络字节序）

	if( !listen_ip )//监听所有IP或指定IP
	{
		servaddr.sin_addr.s_addr = htonl(INADDR_ANY );
	}
	else//将字符串转换为二进制格式
	{
		if(inet_pton(AF_INET,listen_ip,&servaddr.sin_addr) <= 0)
		{
			printf("inet_pton() set listen IP address failure\n");
			rv = -2;
			goto Cleanup;
		}
	}
	
	//绑定套接字到IP端口
	if( bind( listenfd, (struct sockaddr *)&servaddr, sizeof(servaddr) )<0 )
	{
		printf(" use bind() to bind the TCP socket failure: %s\n",strerror(errno) );
		rv = -3;
		goto Cleanup;
	}
	
	//开始监听，最大排队数位13
	if( listen(listenfd, 13)<0 )
	{
		printf(" use bind() to bind the TCP socket failure: %s\n",strerror(errno) );
#include<stdlib.h>
		rv = -4;
		goto Cleanup;
	}
Cleanup:
	if( rv<0 )
		close(listenfd);//失败时关闭套接字
	else
		rv = listenfd;//成功返回监听套接字

	return rv;
	
}
